package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.UsedCar1;
import com.example.demo.entity.UsedCar2;
import com.example.demo.form.UsedCarForm;
import com.example.demo.service.UsedCar1Service;
import com.example.demo.service.UsedCar2Service;

@RestController
@RequestMapping(value = "/usedcar")
public class UsedCar1Controller {
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	@Autowired
	private UsedCar1Service usedCar1DAO;
	
	@Autowired
	private UsedCar2Service usedCar2DAO;
	
	
	
	@RequestMapping(value = "/save")
	private Object save(UsedCarForm Form) throws ParseException {
	  Integer used1Id=Form.getId();
	  UsedCar1 UsedCar1 = new UsedCar1();
	  UsedCar1 usedCar1 = new UsedCar1();
	  UsedCar2 usedCar2 = new UsedCar2();
	  UsedCar2 UsedCar2 = new UsedCar2();
	  Date d= new Date();
	  
	  if(used1Id==null) {
		  UsedCar1.setEsccxmc(Form.getEsccxmc());
		  usedCar1 = usedCar1DAO.save(UsedCar1);
	  }else {
		  usedCar1 = usedCar1DAO.findById(used1Id);
		  usedCar1.setEsccxmc(Form.getEsccxmc());
		  usedCar1 = usedCar1DAO.save(usedCar1);
		  Date d1 = dateFormat1.parse("1999-01-01");
		  List<UsedCar2> list = usedCar2DAO.findByUsedCar(usedCar1);
			for (UsedCar2 UsedCar : list) {
				if(d1.compareTo(UsedCar.getStartDays())==-1) {
					d1=UsedCar.getStartDays();
					UsedCar2=UsedCar;
				}
			}
			UsedCar2.setEndDays(d);
			usedCar2DAO.save(UsedCar2);
	  }
	  	BeanUtils.copyProperties(Form, usedCar2, "id","name");
	   	usedCar2.setUsedCar(usedCar1);
		usedCar2.setStartDays(d);
		usedCar2DAO.save(usedCar2);
		return new AjaxResult("数据保存成功");		
	}
	
	@RequestMapping(value = "/list")
	public Object list() {
		return new AjaxResult(usedCar1DAO.findAll());
	}
	
	@RequestMapping(value = "/findById")
	public Object findbyId(Integer id) throws ParseException {
		List<UsedCar2> list = usedCar2DAO.findByUsedCar(usedCar1DAO.findById(id));


		Date d = dateFormat1.parse("1999-01-01");
		UsedCar2 n= new UsedCar2();
		for (UsedCar2 UsedCar2 : list) {
			if(d.compareTo(UsedCar2.getStartDays())==-1) {
				d=UsedCar2.getStartDays();
			    n=UsedCar2;
			}
		}
		 return new AjaxResult(n);		
	}
}
